<template>
  <div class="container">
    <!-- <header>检查机房</header> -->
    <section class="header-section">
      <el-form :inline="true" class="m-t-1 apply-card ">
        <el-form-item label="医院" label-width="80px">
          <el-select size="small" v-model="listQuery.hospitalCode" @change="changeHosp" placeholder="请选择医院" filterable clearable>
            <el-option
              v-for="item in mx_hospitalList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像区域" label-width="80px" prop="depArea">
          <el-select size="small" v-model="depArea" @change="changeDepArea" placeholder="请选择" clearable multiple>
            <el-option
              v-for="item in depAreaOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查部门" label-width="80px" prop="dep">
          <el-select size="small" v-model="dep" placeholder="请选择" clearable multiple>
            <el-option
              v-for="item in depOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" label-width="80px" prop="dep">
          <el-select size="small" v-model="department" placeholder="请选择" clearable multiple>
            <el-option
              v-for="item in departmentOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机房状态" label-width="80px" prop="dep">
          <el-select size="small" v-model="listQuery.checkRoomState" placeholder="请选择" clearable>
            <el-option
              v-for="item in checkRoomStateOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="m-l-0 " size="small" @click="search" plain><i class="el-icon-search"></i>搜索</el-button>
        </el-form-item>
      </el-form>
    </section>
    <section class="content-section">
      <el-button type="primary" class="m-b-1 m-l-1 floatR" size="small" @click="handleAdd"><i class="el-icon-circle-plus"></i>添加</el-button>
      <el-table size="medium" :data="checkTable" v-loading="loading">
        <el-table-column align="center" label="操作" width="380">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="bindHis(scope.$index, scope.row)"><i class="el-icon-circle-plus"></i>绑定His</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit"></i>编辑</el-button>
            <el-button type="warning" size="small" @click="updateCheckroom(scope.$index, scope.row)"><i class="el-icon-edit"></i>{{scope.row.checkRoomState === '正常' ? '关闭' : '开放'}}</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete"></i>删除</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="checkRoom" label="检查机房" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column align="center" prop="checkRoomState" label="机房状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.checkRoomState === '正常' ? 'success' :'danger'">{{scope.row.checkRoomState}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="dep" label="检查部门"> </el-table-column>
        <el-table-column align="center" prop="modality" label="检查设备"> </el-table-column>
        <el-table-column align="center" prop="department" label="科室"> </el-table-column>
        <el-table-column align="center" prop="depArea" label="影像区域"> </el-table-column>
        <el-table-column align="center" prop="hospitalName" label="医院名称" :show-overflow-tooltip="true"> </el-table-column>
      </el-table>
      <paginationCont
        :total="totalCount"
        :page.sync="currentPage"
        :limit.sync="pageSize"
        @pagination="fetchData"
      />
    </section>
    <check-room-dialog :dialog-visible="dialogVisible" :check-data="curCheckData" @myClose="handleClose"></check-room-dialog>
    <el-dialog
      title="绑定His"
      :visible.sync="bingShow"
      :destroy-on-close="true"
      width="80%"
      top="5vh"
      :fullscreen="false">
      <el-tree
        ref="tree"
        class="m-t-1 tree-dialog"
        :data="filterData"
        show-checkbox
        node-key="id"
        :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bingShow = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getCheckroomPages, deleteCheckroom, getDepAreaList, getDepList, checkroomBindHis, getHisDepTree, getHisRegisterList, getItemList, updateCheckroomState } from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import CheckRoomDialog from './checkRoomDialog.vue'

export default {
  name: 'Checkroom',
  components: {
    paginationCont,
    CheckRoomDialog
  },
  data() {
    return {
      listQuery: {
        hospitalCode: '',
        dep: '',
        depArea: '',
        department: '',
        checkRoomState: ''
      },
      dep: [],
      depArea: [],
      department: [],
      checkTable: [],
      depAreaOptions: [], // 影像区域
      depOptions: [], // 检查部门
      departmentOptions: [],
      checkRoomStateOptions: ['正常', '关闭'],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      curCheckData: undefined, // 当前选中的行
      loading: false,
      bingShow: false,
      checkTypeData: [],
      filterData: [], // 点击编辑以后过滤条件
      defaultProps: {
        children: 'childrens',
        label: 'text'
      },
      curRow: {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.$getHospitalList()
      this.listQuery.hospitalCode = this.mx_hospitalList[0].code || ''
      this.changeHosp()
      this.getHisTree()
      this.fetchData()
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    changeHosp() {
      if (!this.listQuery.hospitalCode) return
      // 关联：影像、检查部门、检查分组、检查设备、检查机房
      let data = { HospitalCode: this.listQuery.hospitalCode }
      getDepAreaList(data).then(res => {
        if (res && res.code === 10000) {
          this.depAreaOptions = res.content.list
          // 检查部门
          this.getDep()
        }
      })
    },
    getDep() {
      let data = {
        HospitalCode: this.listQuery.hospitalCode,
        DepArea: this.depArea.join(',')
      }
      getDepList(data).then(async res => {
        if (res && res.code === 10000) {
          this.depOptions = res.content.list
        }
      })
    },
    changeDepArea() {
      if (this.depArea.length === 0) return
      // 关联：检查部门
      this.getDep()
      this.getDepartment()
    },
    getDepartment() {
      let data = {
        HospitalCode: this.listQuery.hospitalCode,
        DepArea: this.depArea.join(','),
        type: '科室'
      }
      getItemList(data).then(res => {
        if (res && res.code === 10000) {
          this.departmentOptions = res.content.list.map(_item => _item.item)
        }
      })
    },
    fetchData() {
      if (!this.listQuery.hospitalCode) {
        this.$message.warning('请选择医院')
        return
      }
      this.loading = true
      this.listQuery.depArea = this.depArea.join(',')
      this.listQuery.dep = this.dep.join(',')
      this.listQuery.department = this.department.join(',')
      this.listQuery.pageSize = this.pageSize
      this.listQuery.pageNumber = this.currentPage
      getCheckroomPages(this.listQuery).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.checkTable = res.content.list
          this.totalCount = res.content.totalCount
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleDelete(i, row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      // 清空右边
      let data = {
        id: row.id
      }
      deleteCheckroom(data).then(res => {
        if (res && res.code === 10000) {
          this.search()
          this.$message.success('删除成功')
        }
      })
    },
    handleAdd() {
      this.curCheckData = {}
      this.dialogVisible = true
    },
    handleEdit(i, row) {
      this.curCheckData = row
      this.dialogVisible = true
    },
    getHisTree() {
      getHisDepTree({ HospitalCode: this.listQuery.hospitalCode }).then(res => {
        if (res && res.code === 10000) {
          let depNodes = res.content.childrens
          for (let i = 0; i < depNodes.length; i++) {
            let tempLevel1 = { text: depNodes[i].text, level: 1, childrens: [], id: depNodes[i].text }
            // 如果存在部位
            if (depNodes[i].childrens && depNodes[i].childrens.length !== 0) {
              for (let j = 0; j < depNodes[i].childrens.length; j++) {
                let level1Children = depNodes[i].childrens
                // 加上level防止同名
                let tempLevel2 = { text: level1Children[j].text, level: 2, childrens: [], id: level1Children[j].text, parentId: tempLevel1.id }
                if (level1Children[j].childrens && level1Children[j].childrens.length !== 0) {
                  tempLevel2.childrens = level1Children[j].childrens.map(item => {
                    return { text: item.text, level: 3, childrens: [], id: tempLevel2.id + item.text, parentId: tempLevel2.id, grandId: tempLevel2.parentId }
                  })
                }
                tempLevel1.childrens.push(tempLevel2)
              }
            }
            this.checkTypeData.push(tempLevel1)
          }
        }
      })
    },
    bindHis(i, row) {
      this.curRow = row
      this.bingShow = true
      let data = {
        hospitalCode: row.hospitalCode,
        checkRoom: row.checkRoom
      }
      let filterTemp = this.checkTypeData.filter(item => item.id === row.dep)
      this.filterData = filterTemp[0] ? filterTemp[0].childrens : []
      getHisRegisterList(data).then(res => {
        if (res && res.code === 10000) {
          this.checkTreeRow(res.content.list)
        }
      })
    },
    updateCheckroom(i, row) {
      this.$confirm('此操作将修改状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateData(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    updateData(row) {
      let data = {
        id: row.id,
        CheckRoomState: row.checkRoomState === '正常' ? '关闭' : '正常'
      }
      updateCheckroomState(data).then(res => {
        if (res && res.code === 10000) {
          this.$message.success('修改成功')
          this.fetchData()
        }
      })
    },
    // 进行默认勾选
    checkTreeRow(partList) {
      this.$refs.tree.setCheckedKeys([])
      let checkTypeNodes = []
      if (partList.length != 0) {
        for (let i = 0; i < partList.length; i++) {
          // level3
          checkTypeNodes.push({ id: partList[i].bigpart + partList[i].smallpart })
        }
      }
      this.$refs.tree.setCheckedNodes(checkTypeNodes)
    },
    handleConfirm() {
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      // 获取检查部位（level2）
      let bigPart = checkedNodes.filter(item => item.level == 2)
      let bindData = {
        hospitalCode: this.curRow.hospitalCode,
        checkRoom: this.curRow.checkRoom,
        hisParts: []
      }
      for (let i = 0; i < bigPart.length; i++) {
        for (let j = 0; j < bigPart[i].childrens.length; j++) {
          bindData.hisParts.push({
            bigpart: bigPart[i].text,
            smallpart: bigPart[i].childrens[j].text
          })
        }
      }
      checkroomBindHis(bindData).then(res => {
        if (res && res.code === 10000) {
          this.bingShow = false
          this.$message.success('成功绑定')
        }
      })
    },
    handleClose(val) {
      this.dialogVisible = false
      if (val) {
        this.fetchData()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.tree-dialog{
  max-height: 550px;
  overflow-x: auto;
}
</style>
